package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApReadBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Log4j2
public class ApReadBehaviorServiceImpl extends ServiceImpl<ApReadBehaviorMapper, ApReadBehavior> implements ApReadBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        //判断参数  那些统计的时间 前端都会传过来的 直接设置就好
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer userID = AppThreadLocalUtils.getUser().getId();
        //根据id和设备id查询出来行为实体  如果等于null 返回
        ApBehaviorEntry entry = apBehaviorEntryService.findByUserIdOrEquipmentId(userID, dto.getEquipmentId());
        if (entry == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "没有找到行为实体");
        }

        ApReadBehavior read = getOne(Wrappers.<ApReadBehavior>lambdaQuery().eq(ApReadBehavior::getArticleId, dto.getArticleId())
                .eq(ApReadBehavior::getEntryId, entry.getId()));
        //根据行为实体和文章id查询这个阅读表 如果没有 添加 count为1
        if (read == null) {
            ApReadBehavior newRead = new ApReadBehavior();
            newRead.setArticleId(dto.getArticleId());
            newRead.setCount(dto.getCount());
            newRead.setCreatedTime(new Date());
            newRead.setEntryId(entry.getId());
            newRead.setLoadDuration(dto.getLoadDuration());
            newRead.setPercentage(dto.getPercentage());
            newRead.setReadDuration(dto.getReadDuration());
            save(newRead);
        } else {
            //如果有 设置前端传来的值 count是之前数据库里面的count+1 更新时间为new date
            read.setCount((short) (read.getCount() + 1));
            read.setUpdatedTime(new Date());
//            以下这些数据为前端传来最新的统计数据 我认为需要设置 但是老师讲的是不用设置 那就先不设置了
//            read.setLoadDuration(dto.getLoadDuration());
//            read.setPercentage(dto.getPercentage());
//            read.setReadDuration(dto.getReadDuration());
            updateById(read);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}